﻿using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.NetworkAnalysis;
using System.Windows.Forms;

namespace TubeBurstAnalysis
{
#pragma warning disable CS0618 // “BaseTool”已过时:“The assembly containing this class is obsolete.  Reference the ESRI.ArcGIS.ADF.Local assembly instead.”
    internal class ToolFixFaultyValve : BaseTool
#pragma warning restore CS0618 // “BaseTool”已过时:“The assembly containing this class is obsolete.  Reference the ESRI.ArcGIS.ADF.Local assembly instead.”
    {

        private IHookHelper m_hookHelper;

        /// <summary>
        /// 当前的集合网络
        /// </summary>
        private IGeometricNetwork geometricNetwork;

        /// <summary>
        /// 设置当前分析的几何网络
        /// </summary>
        public IGeometricNetwork GeometricNetwork
        {
            set => geometricNetwork = value;
        }

        /// <summary>
        /// 当前分析的地图
        /// </summary>
        private IMap map;

        /// <summary>
        /// 设置当前分析的地图
        /// </summary>
        public IMap Map
        {
            set => map = value;
        }

        /// <summary>
        /// 当前视图
        /// </summary>
        private IActiveView activeView;

        /// <summary>
        /// 设置当前视图
        /// </summary>
        public IActiveView ActiveView
        {
            set => activeView = value;
        }

        public FormAnalysis formResult;

        public ToolFixFaultyValve()
        {
            //
            // TODO: Define values for the public properties
            //
            base.m_category = "爆管分析"; //localizable text 
            base.m_caption = "修复失灵阀门";  //localizable text 
            base.m_message = "在地图上点击阀门，将其标记为正常阀门。";  //localizable text
            base.m_toolTip = "修复失灵阀门";  //localizable text
            base.m_name = "FixFaultyValve";   //unique id, non-localizable (e.g. "MyCategory_MyTool")

        }

        #region 被重写方法

        public override void OnCreate(object hook)
        {
            if (m_hookHelper == null)
            {
                m_hookHelper = new HookHelperClass();
            }

            m_hookHelper.Hook = hook;
        }

        /// <summary>
        /// 移除失灵阀门鼠标点击事件
        /// </summary>
        /// <param name="Button"></param>
        /// <param name="Shift"></param>
        /// <param name="X"></param>
        /// <param name="Y"></param>
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            //获取鼠标点击位置的空间点
            IPoint point = new PointClass();
            IActiveView activeView = m_hookHelper.ActiveView;
            point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
            IMap map = m_hookHelper.FocusMap;

            //IPointToEID接口用来通过空间点获取该位置的几何网络元素
            IPointToEID pointToEID = new PointToEIDClass
            {
                GeometricNetwork = geometricNetwork,
                SourceMap = map,
                SnapTolerance = 10
            };
            //通过IPointToEID接口的GetNearestJunction方法获取点击位置最邻近的管点元素
            int nearestJunctionEID = -1;
            IPoint outPoint = new PointClass();
            pointToEID.GetNearestJunction(point, out nearestJunctionEID, out outPoint);
            //如果获取得到管点元素
            if (outPoint != null)
            {
                //利用netElements查询最近管点EID对应的userClassID、userID
                INetElements netElements = geometricNetwork.Network as INetElements;
                netElements.QueryIDs(nearestJunctionEID, esriElementType.esriETJunction, out int userClassID, out int userID, out int userSubID);
                //根据userClassID、userID得到管点要素，判断是否为阀门,如果不是，直接退出
                IFeatureClass featureClass = GetFeatureClassByID(userClassID, map);
                IFeature selectedPoint = featureClass.GetFeature(userID);
                string SUBSID = selectedPoint.get_Value(selectedPoint.Fields.FindField("SUBSID")).ToString();
                int ObjectId = selectedPoint.OID;
                if (SUBSID != "阀门")
                {

                    MessageBox.Show("请选择阀门类型的管点");
                    return;
                }

                //设置失灵阀门标识其ENABLED属性为1，代表水流无法从这里截断
                //获取工作空间
                IDataset dataset = featureClass as IDataset;
                IWorkspace workspace = dataset.Workspace;
                IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;
                workspaceEdit.StartEditing(false);
                workspaceEdit.StartEditOperation();
                //修改属性
                int fieldID = selectedPoint.Fields.FindField("ENABLED");
                if ((short)selectedPoint.get_Value(fieldID) == 0)
                {
                    MessageBox.Show("请选择失灵的阀门");
                    return;
                }
                selectedPoint.set_Value(fieldID, 0);
                selectedPoint.Store();
                //停止编辑
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(true);

                //修该阀门后添加所选点
                formResult.listTargetValves.Add(selectedPoint);
                //遍历，从失灵阀门中删除目标阀门
                for (int i = 0; i < formResult.listFaultyValves.Count; i++)
                {
                    if (formResult.listFaultyValves[i].OID == selectedPoint.OID)
                    {
                        formResult.listFaultyValves.Remove(formResult.listFaultyValves[i]);
                        // break;
                    }
                }
                //根据目标阀门列表和失灵阀门列表，生成两个listBox中的显示列表并显示
                formResult.start();
                //刷新视图
                activeView.Refresh();
            }
        }

        /// <summary>
        /// 根据ID获取FeatureClass
        /// </summary>
        /// <param name="userClassID"></param>
        /// <param name="map"></param>
        /// <returns></returns>
        private IFeatureClass GetFeatureClassByID(int userClassID, IMap map)
        {
            IFeatureClass featureClass = null;
            for (int i = 0; i < map.LayerCount; i++)
            {
                featureClass = ((IFeatureLayer)map.get_Layer(i)).FeatureClass;
                if (featureClass.FeatureClassID == userClassID)
                {
                    return featureClass;
                }
            }
            return null;
        }

        #endregion

    }
}
